'''
The module overrides U{twisted.internet.base  <http://twistedmatrix.com>}
module in Twisted framework library..

@author: Hatem Oraby
'''




def __SignalReactorMixinMainLoop(self):
    '''
    The method
    overrides U{twisted.internet.base._SignalReactorMixin.mainloop
    <http://twistedmatrix.com>}.
    
    The method converts the original method loop into one 
    iteration then returns back the next timeout of the next event.
     
    Also the method checks if we need to re-schedule the current
    module again.
    '''
    keepLooping = True
    while keepLooping and self._started:
        try:
            # Advance simulation time in delayed event
            # processors.
            self.runUntilCurrent()
            t2 = self.timeout() #Get the time to the closest recent call
                                # if no calls left then None is returned
            t = self.running and t2
            self.doIteration(t) #See what's new with inherting class --
                                # (In select, see what's new readings and 
                                #  and writing exists in the sockets)                                    
        except:
            from twisted.internet.base import log
            log.msg("Unexpected error in main loop.")
            log.err()
        else:
            if self._stopped:
                from twisted.internet.base import log
                log.msg('Main loop terminated.')
        
        keepLooping = False
        if self.timeout() == 0:
            keepLooping = True
        
        #Check if writer socket requires a write, if it does
        # then we schedule it to run again.
        if not keepLooping:#Little optimization
            for writer in self._writes.keys():
                #sktObj = Module.current.getFileNo(self._writes[writer]) 
                if writer.socket.isNewWrite():  #And there is buffer available
                    #I need only to find one writer
                    keepLooping = True
                    break
                
        import socket #Bad practice, include it above
        if not keepLooping:
            for reader in self._reads.keys():
                #make sure that it's our type of socket,not unix reader
                if type(reader) == socket.socket:
                    if reader.socket.isNewRead():
                        keepLooping = True
                        break
    #end of while loop

def InstallSignalReactor():
    '''Install all the overriding modules '''
    import twisted.internet.base as base
    from twistedSim.overrideManager import OverrideManager
    OverrideManager.storeEntity(originalFn = base._SignalReactorMixin.mainLoop,
                fullName = "twisted.internet.base._SignalReactorMixin.mainLoop")
    #base._SignalReactorMixin.run = __run
    base._SignalReactorMixin.mainLoop = __SignalReactorMixinMainLoop
